<?php
/*   
编辑者:写php的黄瓜兄
创建日期:2019.4.22
创建控制器/方法:提现
*/

namespace app\inter\controller;
use think\Config;
use think\console\command\make\Model;
use  think\Controller;
use think\Db;
use think\Debug;
use think\Log;
use think\Session;

class Word extends Controller
{
    const TOPIC_TYPE = [
        '《单选题》' => 1,
        '《多选题》' => 2,
        '《判断题》' => 3,
        '《填空题》' => 4,
        '《解答题》' => 5,
        '《计算题》' => 6,
        '《证明题》' => 7,
        '《应用题》' => 8,
        '《阅读题》' => 9,
        '《综合题》' => 10,
    ];
    const DEGREE_TYPE = [
        '易' => 1,
        '中' => 2,
        '难' => 3,
    ];
    const MATCHING_TYPE = [
        '【题干】' => 1,
        '【答案】' => 2,
        '【解析】' => 3,
        '【难度】' => 4,
        '【知识点】' => 5,
        '【题目】' => 6,
        '【选项】' => 7,
    ];

    //上传组卷
     public  function  daoAddPaper()
     {
         Db::startTrans();
         try{
                 $test_paper_id = intval($_POST['test_paper_id']);
                 $grade_id = intval($_POST['grade_id']);
                 $subject_id = intval($_POST['subject_id']);
//             $test_paper_id = 6;
//             $grade_id = 1000;
//             $subject_id = 10000;
                 /*if(empty($test_paper_id) || empty($grade_id)  || empty($subject_id)){
                     return json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
                 }*/
                 if(!$_FILES['test_paper']['tmp_name']) return json(['data'=>'', 'msg'=>'文件不能为空', 'state'=>10002]);
                 $dir = UPLOAD_FILE_PATH . "doc/word/" . date('YmdHis') . "_" . rand(10000, 99999);
                 if (!file_exists($dir)) {
                     mkdir($dir, 0777, true);
                 }
                 $file_name = date("YmdHis") . "_" . rand(1000, 10000);
                 $ret = copy($_FILES['test_paper']['tmp_name'], $dir . "/" . $file_name . "_doc.docx");
                 $ret = copy($_FILES['test_paper']['tmp_name'], $dir . "/" . $file_name . "_doc.zip");
                 $ret_s = shell_exec("chmod 755 " . $dir . "/" . $file_name . "_doc.zip");
                 chdir($dir);
                 $ret_shell = shell_exec("/usr/bin/unzip " . $file_name . "_doc.zip");
                 $path_arr = explode('public', $dir);
//         $ret_shell = shell_exec('ls /');
//        var_dump($ret_shell);
//        var_dump($file_name);
//         exit();

//         var_dump(UPLOAD_FILE_PATH);exit();
                 $xmlNode = simplexml_load_file($dir . "/word/_rels/document.xml.rels");
//                 $xmlNode = simplexml_load_file(UPLOAD_FILE_PATH . "doc/word/_rels/document.xml.rels");
                 $arrayData = xmlToArray($xmlNode);
                 $data = json_encode($arrayData);
                 $img_arr = [];
                 foreach ($arrayData['Relationships']['Relationship'] as $k => $v) {
                     $img_arr[$v['@Id']] = $v['@Target'];
                 }
//             echo json_encode($img_arr);exit();


// 打开文件并读取数据并关闭
                 $fp = fopen($dir . "/word/document.xml", 'r');
                 $xmldata = fread($fp, filesize($dir . "/word/document.xml"));
                 fclose($fp);

// 节点上的分隔符
                 $flag = "②";

// 如果节点有值，那么#text就叫做textValue属性
                 $valueTextName = "textValue";

                 $json = xmlStr_to_json($xmldata, $valueTextName, $flag);

//print_r($json);
//exit();
                 $json_arr = json_decode($json, true);
                 $text_arr = [];
                 foreach ($json_arr['w:document②1']['w:body②2'] as $k1 => $v1) {
//    echo $k1 . "\n";
                     echo "\n";
                     $text = '';
                     foreach ($v1 as $k2 => $v2) {
                         if (is_array($v2)) {
                             foreach ($v2 as $k3 => $v3) {
                                 if (strpos($k3, 'w:t') !== false) {
//                    if (isset($v3['textValue'])) echo $v3['textValue'];
                                     if (isset($v3['textValue'])) $text .= $v3['textValue'];

                                 }

                                 if (strpos($k3, 'w:drawing') !== false) {
                                     $key_arr = explode('②', $k3);
                                     $num = $key_arr[1] + 1;
                                     foreach ($v3['wp:inline②' . $num] as $k4 => $v4) {
                                         if (strpos($k4, 'a:graphic') !== false) {
                                             foreach ($v4 as $k5 => $v5) {
                                                 if (strpos($k5, 'a:graphicData') !== false) {
                                                     foreach ($v5 as $k6 => $v6) {
                                                         if (strpos($k6, 'pic:pic') !== false) {
                                                             foreach ($v6 as $k7 => $v7) {
                                                                 if (strpos($k7, 'pic:blipFill') !== false) {
                                                                     foreach ($v7 as $k8 => $v8) {
                                                                         if (strpos($k8, 'a:blip') !== false) {
//                                                            echo $v8['r:embed'] . "&&";
                                                                             $text .= "<img src='" . $path_arr[1] . "/word/" . $img_arr[$v8['r:embed']] . "' />";
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }

                             }

                         }
//        echo "\n";
                     }
                     $text_arr[] = $text;
                 }

//             return  json(['data'=>$text_arr, 'msg'=>'未找到', 'state'=>10000]);

                 //试卷更新

                 Db::table('test_paper')->where('id', $test_paper_id)
                     ->update(['word_file_url' => $path_arr[1] . "/" . $file_name . "_doc.docx"]);

                 $topic_type = 0;  //题目类型
                 $topic_question = ''; //题目
                 $stem = '';  //题干
                 $options = []; //选项
                 $answer = '';  //答案
                 $analysis = ''; // 解析
                 $degree = ''; // 难度
                 $knowledge = ''; //知识点
                 $matching_type = 0;
                 $pid = 0;
                 $topic_type_key = array_keys(self::TOPIC_TYPE);
                 $matching_type_key = array_keys(self::MATCHING_TYPE);
                 $degree_type_key = array_keys(self::DEGREE_TYPE);
                 $hb_arr = array_merge($topic_type_key, $matching_type_key);
                 $topic_id = 0;
                 $topic_pid_id = 0;

                 foreach ($text_arr as $k => $v) {
                     $match_content = trim($v);
                     if (empty($match_content)) {
                         continue;
                     }






                     //题干
                     if ($match_content == "【题干】") $topic_pid_insert = 0;
                     if ($matching_type == 1 && !in_array($match_content, $hb_arr)) {
                         if ($topic_pid_id) {  //
                             $data = Db::table('topic')->where('id', $topic_pid_id)->find();
                             $content = json_decode($data['content'], true);
                             $content[] = $match_content;
                             $save = ['content' => json_encode($content)];
                             Db::table('topic')->where('id', $topic_pid_id)->update($save);
                         } else {
                             $content = [$v];
                             $topic_pid_insert = [
                                 'type' => $topic_type,
                                 'grade_id' => $grade_id,
                                 'subject_id' => $subject_id,
                                 'crt_user' => 1000,
                                 'crt_time' => time(),
                                 'is_correct' => 0,
                                 'content' => json_encode($content)
                             ];
                             $topic_pid_id = Db::table('topic')->insert($topic_pid_insert, true, true);
                             $test_paper_topic = [
                                 'test_paper_id' => $test_paper_id,
                                 'topic_id' => $topic_pid_id,
                                 'crt_time' => time(),
                             ];
                             Db::table('test_paper_topic')->insert($test_paper_topic, true, true);
                         }
                     }
                     //题目
                     if ($match_content == "【题目】") $topic_id = 0;
                     if ($matching_type == 6 && !in_array($match_content, $hb_arr)) {
                         if ($topic_id) {
                             $data = Db::table('topic')->where('id', $topic_id)->find();
                             $content = json_decode($data['content'], true);
                             $content[] = $match_content;
                             $save = ['content' => json_encode($content)];
                             Db::table('topic')->where('id', $topic_id)->update($save);
                         } else {
                             $content = [$v];
                             $topic_insert = [
                                 'pid' => $topic_pid_id,
                                 'type' => $topic_type,
                                 'grade_id' => $grade_id,
                                 'subject_id' => $subject_id,
                                 'crt_user' => 1000,
                                 'crt_time' => time(),
                                 'is_correct' => 0,
                                 'content' => json_encode($content)
                             ];
                             $topic_id = Db::table('topic')->insert($topic_insert, true, true);
                             $test_paper_topic = [
                                 'test_paper_id' => $test_paper_id,
                                 'topic_id' => $topic_id,
                                 'crt_time' => time(),
                             ];
                             Db::table('test_paper_topic')->insert($test_paper_topic, true, true);
                         }
                     }
                     //选项
                     if ($matching_type == 7 && !in_array($match_content, $hb_arr)) {
                         $sort_arr = explode('、', $match_content);
//                 var_dump($sort_arr);exit();
                         $branch_insert = [
                             'topic_id' => $topic_id,
                             'brch_order' => $sort_arr[0],
                             'is_answer' => $topic_id,
                             'brch_content' => $match_content,
                         ];
                         Db::table('topic_branch')->insert($branch_insert, true, true);
                     }
                     //答案
                     if ($matching_type == 2 && !in_array($match_content, $hb_arr)) {
                         if (!$topic_id) return json(['data' => '', 'msg' => '上传试卷失败', 'state' => 10002]);
                         $data = Db::table('topic')->where('id', $topic_id)->find();
                         $content = json_decode($data['answer'], true);
                         $content[] = $match_content;
                         $save = ['answer' => json_encode($content)];
                         Db::table('topic')->where('id', $topic_id)->update($save);
                     }
                     //解析
                     if ($matching_type == 3 && !in_array($match_content, $hb_arr)) {
                         if (!$topic_id) return json(['data' => '', 'msg' => '上传试卷失败', 'state' => 10003]);
                         $data = Db::table('topic')->where('id', $topic_id)->find();
                         $content = json_decode($data['analysis'], true);
                         $content[] = $match_content;
                         $save = ['analysis' => json_encode($content)];
                         Db::table('topic')->where('id', $topic_id)->update($save);
                     }
                     //难度
                     if ($matching_type == 4 && !in_array($match_content, $hb_arr)) {
                         if (in_array($match_content, $degree_type_key)) {
                             $save = [
                                 'degree' => self::DEGREE_TYPE[$match_content]
                             ];
                             Db::table('topic')->where('id', $topic_id)->update($save);
                         }
                     }
                     //知识点
                     if ($matching_type == 5 && !in_array($match_content, $hb_arr)) {
                         $knowledge = Db::table('knowledge')
                             ->where('name', 'like', "%" . $match_content . "%")
                             ->find();
                         if ($knowledge) {
                             $topic_knowledge_insert = [
                                 'topic_id' => $topic_id,
                                 'knowledge_id' => $knowledge['id'],
                                 'crt_time' => time(),
                             ];
                             Db::table('topic_knowledge')->insert($topic_knowledge_insert);
                         }
                     }

                     //题型
                     if (in_array($match_content, $topic_type_key)) {
                         $topic_type = self::TOPIC_TYPE[$match_content];
                         continue;
                     }
                     //关键字
                     if (in_array($match_content, $matching_type_key)) {
                         $matching_type = self::MATCHING_TYPE[$match_content];
                         continue;
                     }


                 }
//                 echo json_encode($text_arr);



             Db::commit();
         }catch(\Exception $e){
             Db::rollback();
             return json(['data'=>'', 'msg'=>'上传失败', 'state'=>10001]);
         }
         //修改试卷状态
         $ret2 = Db::table('test_paper')->where(['id' => $test_paper_id])
             ->update(['state' => 2]);
         return json(['data'=>'', 'msg'=>'success', 'state'=>10000]);
     }



    //创建试卷
    public function createTestPaper(){
        if(!isset($_POST['title'])
        || !isset($_POST['grade_id'])
        || !isset($_POST['subject_id'])
        || !isset($_POST['scope'])
        || !isset($_POST['degree'])
        || !isset($_POST['process_time'])
        )  return json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $title = $_POST['title'];
        $grade_id = $_POST['grade_id'];
        $subject_id = $_POST['subject_id'];
        $scope = $_POST['scope'];
        $degree = $_POST['degree'];
        $process_time = $_POST['process_time'];
        $ret = Db::table('test_paper')->where(['title' => $title])->find();
        if($ret)  return json(['data'=>'', 'msg'=>'此试卷名称重复', 'state'=>-2]);
        $insert_data = [
            'title' => $title,
            'grade_id' => $grade_id,
            'subject_id' => $subject_id,
            'scope' => $scope,
            'process_time' => $process_time,
            'degree' => $degree,
            'crt_user' => 10000,
            'crt_time' => time(),
            'is_edit' => 1,
            'status' => 0,
            'state' => 1,
        ];
        $ret = Db::table('test_paper')->insert($insert_data, true, true);
        if($ret){
            return json(['data'=>'','test_paper_id' => $ret, 'msg'=>'success', 'state'=>10000]);
        }else{
            return json(['data'=>'',  'msg'=>'创建失败', 'state'=>10003]);
        }

    }

    public function getTestPaperList(){
        $param = $this->request->param();
        $subject = Config::get('subject');
        $grade = Config::get('grade');
        $class = Config::get('class');
        $where['crt_user'] = $param['crt_user'];
        if(isset($_POST['state'])) $where['state'] = $_POST['state'];
        if(isset($_POST['is_collect'])){
            $collect_list = Db::table('collect')
                ->where(['uid' => $param['crt_user']])->select();
            $collect_id_arr = [];
            foreach($collect_list as $k => $v){
                $collect_id_arr[] = $v['test_paper_id'];
            }
            $where['id'] = ['IN', join(',', $collect_id_arr)];
        }
        if(!empty($param['scope'])) $where['scope'] = $_POST['scope'];
        if(!empty($param['keyword'])) $where['title'] = ['LIKE', "%{$param['keyword']}%"];
        $list = Db::table('test_paper')
            ->where($where)->select();
        if($list){
            foreach($list as &$item){
                isset($grade[$item['grade_id']]) ? $item['grade_label'] = $grade[$item['grade_id']] : $item['grade_label']='';
                isset($subject[$item['subject_id']]) ? $item['subject_label'] = $subject[$item['subject_id']] : $item['subject_label'] = '';
                $item['crt_time'] = $item['crt_time']?date('Y-m-d', $item['crt_time']):'';
                $user_data = Db::table('sys_user')->where(['user_id' => $item['crt_user']])->find();
                if($user_data){
                    $item['crt_username'] = $user_data['name'];
                }else{
                    $item['crt_username'] = '';
                }
            }
            foreach($list as &$item){
                $collect_list = Db::table('collect')
                    ->where(['test_paper_id' => $item['id']])->find();
                if($collect_list){
                    $item['is_collect'] = 1;
                }else{
                    $item['is_collect'] = 0;
                }
            }

            foreach($list as &$item){
//                $ret = Db::table('exam_plan')->where(['test_paper_id' => $item['id']])->find();
                $ret1 = Db::table('collect')->where(['test_paper_id' => $item['id'], 'uid' => $param['crt_user']])
                    ->find();
                $item['is_collect'] = $ret1?1:0;
            }

            return json(['data'=>$list, 'msg'=>'success', 'state'=>10000]);
        }else{
            return  json(['data'=>'', 'msg'=>'未找到', 'state'=>10003]);
        }
    }

    public function getPaperDetail(){
        $param = $this->request->param();
        if(empty($param['test_paper_id'])) return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $topic_type = Config::get('topic_type');
        $test_paper_data = Db::table('test_paper')->where(['id' =>  $param['test_paper_id']])->find();
        $sql = "SELECT b.id, b.content, b.type FROM `test_paper_topic` AS a
LEFT JOIN topic AS b ON b.id=a.topic_id
WHERE a.test_paper_id={$param['test_paper_id']} AND b.pid=0 ORDER BY b.id ASC;";
        $topic_list = Db::query($sql);
        $result = [];
        $content = [];
        foreach ($topic_list as &$item) {

            $item['content'] = json_decode($item['content'], true);
            $branch_list = Db::table('topic_branch')->field('brch_content')->where(['topic_id' => $item['id']])->select();
            if($branch_list){
                $item['branch_list'] = array_column($branch_list, 'brch_content');
            }


            $result[$item['type']][] = $item;
            $sql = "SELECT id,content,type FROM  topic
WHERE pid={$item['id']} ORDER BY id ASC;";
            $son_data = Db::query($sql);
            if($son_data){
                foreach($son_data as &$v1){
                    $branch_list = Db::table('topic_branch')->field('brch_content')->where(['topic_id' => $v1['id']])->select();
                    if($branch_list)
                        $v1['branch_list'] = array_column($branch_list, 'brch_content');
                    $v1['content'] = json_decode($v1['content'], true);
                    $result[$item['type']][] = $v1;
                }

            }


        }

        $data = [];
        foreach($result as $k => $v){
            $data[] = [
                'type_label' =>  $topic_type[$k],
                'type' => $k,
                'data' => $v
            ];
        }

        return json(['data'=>$data, 'msg'=>'success', 'state'=>10000]);
    }


    public function delTestPaper(){
        $param = $this->request->param();
        if(!isset($param['id']))
            return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $exam_plan_data = Db::table('exam_plan')->where(['test_paper_id' => $param['id']])->find();
        if($exam_plan_data)
            return  json(['data'=>'', 'msg'=>'考试计划绑定了试卷', 'state'=>10002]);
        $ret = Db::table('test_paper')->where(['id' => $param['id']])->delete();
        if($ret){
            return json(['msg'=>'success', 'state'=>10000]);
        }else{
            return json(['msg'=>'删除失败', 'state'=>10001]);
        }
    }

    public function collectTestPaper(){
        $param = $this->request->param();
        if(!isset($param['id']))
            return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        if(!isset($param['crt_user']))
            return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $data = Db::table('collect')->where(['uid' => $param['crt_user'], 'test_paper_id' => $param['id']])
            ->find();
        if(!$data){
            $data = [
                'uid' => $param['crt_user'],
                'test_paper_id' => $param['id'],
                'status' => 1,
            ];
            Db::table('collect')->insert($data);
            return json(['msg'=>'success', 'state'=>10000]);
        }else{
            return json(['msg'=>'已经收藏', 'state'=>10001]);
        }
    }



    public function getKnowledgeList(){
        $param = $this->request->param();
        if(!isset($param['subject_id']))
            return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        if(!isset($param['grade_id']))
            return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $list = Db::table('knowledge')->field('id,name')->where([
            'subject_id' => $param['subject_id'],
            'grade_id' => $param['grade_id'],
        ])->select();
        return json(['data' => $list, 'msg'=>'success', 'state'=>10000]);

    }

    const CHOSE_ARR = [
        0 => 'A',
        1 => 'B',
        2 => 'C',
        3 => 'D',
    ];

    //人工组卷
    public function manualAddPaper(){
        $param = $this->request->param();
//        return  json($param);
        if (!isset($param['subject_id'])
            || !isset($param['crt_user'])
            || !isset($param['grade_id'])
            || !isset($param['test_paper_id'])
        )
            return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        Db::startTrans();
        try{
            foreach($param['topic_data'] as $k => $v){
                $topic_insert = [
                    'type' => 0,
                    'degree' => $param['race'],
                    'grade_id' => $param['grade_id'],
                    'subject_id' => $param['subject_id'],
                    'crt_user' => $param['crt_user'],
                    'crt_time' => time(),
                    'is_correct' => 0,
                    'content' => json_encode($v['questionStem']),
                    'answer' => '',
                ];
                $ret = Db::table('topic')->insert($topic_insert, true, true);
                if($ret){
                    $test_paper_topic_insert = [
                        'test_paper_id' => $param['test_paper_id'],
                        'topic_id' => $ret,
                        'crt_time' => time(),
                    ];
                    $ret1 = Db::table('test_paper_topic')->insert($test_paper_topic_insert, true, true);
                  /*  if($param['type'] == 1 || $param['type'] == 2){
                        foreach($v['brch_content'] as $k1 => $v1){
                            $topic_branch_insert = [
                                'topic_id' => $ret,
                                'brch_order' => $k1,
                                'brch_content' => $v1,
                            ];
                            $ret2 = Db::table('topic_branch')->insert($topic_branch_insert);
                        }
                    }*/
                    $daan = '';
                    if(is_array($v['answers'])){
                        foreach($v['answers'] as $k1 => $v1){
                            $topic_branch_insert = [
                                'topic_id' => $ret,
                                'brch_order' => $k1,
                                'brch_content' => $v1['content'],
                            ];
                            $ret2 = Db::table('topic_branch')->insert($topic_branch_insert);
                            if($v1['checked']) $daan= self::CHOSE_ARR[$k1];
                        }
                    }else{
                        $daan = $v['answers'];
                    }

                    $ret4 = Db::table('topic')->where(['id' => $ret])->save([
                        'answer' => $daan,
                        'state' => 2
                    ]);
                    if($ret4 === false)
                        return json(['data'=>'', 'msg'=>'人工组卷失败-2', 'state'=>10001]);
                    /*$knowledge_insert = [
                        'topic_id' => $ret,
                        'knowledge_id' => $v['knowledge_id'],
                    ];
                    $re4 = Db::table('test_paper_topic')->insert($knowledge_insert, true, true);*/
                }else{
                    return json(['data'=>'', 'msg'=>'人工组卷失败', 'state'=>10001]);
                }
            }


            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return json(['data'=>'', 'msg'=>'人工组卷失败', 'state'=>10001]);
        }

        return json(['data'=>'', 'msg'=>'success', 'state'=>10000]);

    }
  
  
}